package com.wzw.springboot.principle.use.datasource;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author Wangzhiwen
 */
public class DynamicDataSourceContextHolder {

    private static final ThreadLocal<Deque<String>> CONTEXT = ThreadLocal.withInitial(ArrayDeque::new);

    /**
     * 获得当前线程数据源
     */
    public static String peek() {
        return CONTEXT.get().peek();
    }

    /**
     * 设置当前线程数据源
     */
    public static void push(String dataSource) {
        CONTEXT.get().push(dataSource);
    }

    /**
     * 清空当前线程数据源
     */
    public static void poll() {
        Deque<String> deque = CONTEXT.get();
        deque.poll();
        if (deque.isEmpty()) {
            CONTEXT.remove();
        }
    }

}
